<template>
  <uni-file-picker
    :limit="limit"
    v-model="valueList"
    @select="imgSelect"
    @delete="listRemove"
    :readonly="readonly"
  ></uni-file-picker>
</template>

<script setup lang="ts">
import envConfig from '@/environments'

interface imageProps {
  limit?: number
  readonly?: boolean
  value?: [string]
}
const { url: baseUrl } = envConfig

const { limit, readonly, value } = defineProps<imageProps>()
const emit = defineEmits<{ (e: 'input', val: any): void; (e: 'fail', val: any): void }>()

const valueList = ref([] as unknown as { [name: string]: string }[] | undefined)
const files = ref([] as unknown as string[])
const list = ref([] as unknown as any[])

watch(
  () => value,
  val => {
    if (val) {
      const newList = val.map(item => {
        const file = {
          name: item,
          extname: item.substring(item.lastIndexOf('.') + 1),
          url: item,
        }
        return file
      })

      valueList.value = newList
    }
  },
  { deep: true }
)

const imgSelect = (e: any) => {
  e.tempFiles.forEach((item: string, index: number) => {
    uni.uploadFile({
      url: baseUrl + '/sysCommon/upload/image/singleUpload',
      header: {
        token: uni.getStorageSync('token'),
      },
      name: 'file',
      filePath: e.tempFilePaths[index],
      success: res => {
        if (res?.data) {
          files.value.push(baseUrl + JSON.parse(res.data).data.fileRelativePath)
          emit('input', files.value)
          list.value.push(item)
        }
      },
      fail: fail => {
        emit('fail', fail)
      },
    })
  })
}

const listRemove = () => {}
</script>

<style lang="scss" scoped></style>
